package system

import (
	"fresh-shop-gin/global"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID   int64  `json:"id" gorm:"primaryKey;comment:用户ID"`
	UserName string `json:"userName" gorm:"type:varchar(100);unique;not null;comment:用户名"`
	Password string `json:"password" gorm:"type:varchar(100);not null;comment:密码"`
	Role     []Role `json:"role" gorm:"many2many:sys_user_role;"`
	global.GlobalModel
}

// 密码加密
func (u *User) HashPassword() error {
	hashed, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashed)
	return nil
}

// 密码验证
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

func (User) TableName() string {
	return "sys_users"
}

// 自定义迁移逻辑
func (u *User) Migrate() error {
	if err := global.DB.AutoMigrate(&u); err != nil {
		return err
	}
	return nil
}
